import {
  getWorkBenchData,
  getPatientByTeacher,
  getPatientByDoctor,
} from '../../api/index'
import {
  findTypeByValue,
  pathologicalStagingType
} from '../../utils/type';

const app = getApp()
Page({
  data: {
    active: 0,
    logined: true,
    baseCls: 'page_account',
    avatar_icon: '/assets/images/avatar.png',
    tab_active: 1,
    tab_active_name: 0,
    activeName: 1,
    isDoctor: false,
    myPatient: {
      Finish: 0,
      Focus: 0,
      onGoing: 0,
      Total: 0
    },
    groupAides: [],
    filterGroupAides: [],
    text: {
      doctor: {
        chose: '选择患教',
        title: '患教专员'
      },
      teacher: {
        chose: '选择医生',
        title: '医生'
      }
    },
    searchValue: ''
  },
  onShow() {
    this.getTabBar().init();
    let userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      let type = userInfo.type.label
      let isDoctor = type === '医生'
      let text = isDoctor ? this.data.text.doctor : this.data.text.teacher;
      this.setData({
        logined: true,
        show: false,
        userInfo,
        isDoctor,
        usedText: text
      })
      this.AllPatient();
      this.workBenchData();
    }
  },

  onChangeSearch(e){
    this.setData({
      searchValue: e.detail,
    });
  },

  searchClear() {
    this.AllPatient();
  },
  
  /**
   * 搜索患者列表
   * */
  onSearch(e){
    this.AllPatient(+this.data.tab_active_name)
  },

  onChange(event) {
    this.setData({
      filterGroupAides: [],
      tab_active: event.detail.index,
      tab_active_name: event.detail.name
    })
    this.clear()
    this.AllPatient(+event.detail.name)
  },

	workBenchData() {
		let that = this;
    getWorkBenchData().then(res => {
      const { finish, follow, progress, task, total } = res.data;

      that.setData({
        'myPatient.onGoing': progress,
        'myPatient.Finish': finish,
        'myPatient.Focus': follow,
        'myPatient.Total': total
      })
    }).catch(res => {
      if(res.code === 401){
        that.handleLoginAction(false)
      }
    })
  },

  collapse_onChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },

  /*
   * 获取患教选择值 / fldaJHvNvLgwI
   */
  getSelectProject(e) {
    var id = e.detail.value.id + '';
    const filterGroupAides = this.data.groupAides.filter(item => {
      return item.id == id
    })
    this.setData({
      filterGroupAides
    })
  },

  
  /**
   * 所有患者 
   */
  AllPatient(status) {
    let apiFunc = this.data.isDoctor ? getPatientByDoctor : getPatientByTeacher
    let params = {}

    // 搜索条件
    let searchValue = this.data.searchValue
    if(searchValue){
      params.realName = searchValue
    }

    // 分类
    status = typeof status === 'undefined' ? '0' : status;
    params.status = status

    apiFunc(params).then(res => {
      var AllPatient = res.rows;
      res.rows.forEach(item => {
        item.pathologicalStaging = findTypeByValue(item.pathologicalStaging, pathologicalStagingType)
      })
      this.setData({
        AllPatient: AllPatient,
        AllPatientData: AllPatient
      })

      setTimeout(() => {
        const {
          groupPatients
        } = this.groupPatients();

        this.setData({
          groupAides: groupPatients,
          filterGroupAides: groupPatients
        })
        console.log(groupPatients);
      }, 100)

    })
  },

  groupPatients(){
    const AllPatient = this.data.AllPatient
    if(AllPatient && AllPatient.length > 0){
      const groupingAides = {}
      for(let i = 0;i < AllPatient.length; i++){
        let item = AllPatient[i]
        const distinctId = this.data.isDoctor ? 'teacherId' : 'doctorId'
        const distinctName = this.data.isDoctor ? 'teacherName': 'doctorName'
        let id = item[distinctId];

        if(!groupingAides[id]){
          groupingAides[id] = {
            id: id,
            name: item[distinctName],
          }
          groupingAides[id]['patient-' + this.data.tab_active_name] = []
        }
        groupingAides[id]['patient-' + this.data.tab_active_name].push(item)
      }
      const res = []
      for (const key in groupingAides) {
        if (groupingAides.hasOwnProperty.call(groupingAides, key)) {
          const element = groupingAides[key];
          res.push(element)
        }
      }
      return {
        groupPatients: res
      }
    }
    return {
      groupPatients: [],
    }
  },

  /*
   * 详情
   */
  patient_info(e) {
    wx.navigateTo({
      url: '/pages/patientInfo/index?id=' + e.currentTarget.dataset.id
    })
  },
  clear(){
    var AideBox = this.selectComponent('#AideBox');
    AideBox.setData({
      value: ''
    })
  },

  /*
   * 检索条件重置
   */
  reset() {
    this.clear()
    this.setData({
      filterGroupAides: this.data.groupAides
    })
  },
  
  /**
   * 跳转首页
   */
  goHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
})